import { mockProducts, mockUsers, mockAdminUsers, mockRoles, permissions, mockCategories } from './mockData';
import { getProducts, setProducts, getAdminOrders, setAdminOrders, 
  getCategories, setCategories, getAdminUsers, setAdminUsers,
  getRefunds, setRefunds, getLogs, addLog, updateAdminOrder, getOrders, setOrders,
  getUsers, setUsers, addUser } from '../utils/storage';
import { encryptPassword, getAdminToken, getUserToken } from '../utils/auth'; // 确保导入加密函数
import { 
  addOrder as addOrderToStorage,
} from '../utils/storage';
// API基础配置
const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:3000/api';

// 通用请求方法 - 区分前台和后台认证
const request = async (url, options = {}, isAdmin = false) => {
  const token = isAdmin ? getAdminToken() : getUserToken();
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      ...(token && { Authorization: `Bearer ${token}` }),
    },
  };

  const finalOptions = {
    ...defaultOptions,
    ...options,
    headers: {
      ...defaultOptions.headers,
      ...options.headers,
    },
  };

  try {
    const response = await fetch(`${API_BASE_URL}${url}`, finalOptions);
    const data = await response.json();
    
    if (!response.ok) {
      throw new Error(data.message || '请求失败');
    }
    
    return data;
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
};

// 延迟函数，模拟网络请求
const delay = (ms = 300) => new Promise(resolve => setTimeout(resolve, ms));

// 创建响应对象
const createResponse = (data, success = true, message = '') => ({
  success,
  data,
  message
});

// 认证相关API
export const authAPI = {
  // 管理员登录
  adminLogin: async (username, password) => {
    await delay();
    
    console.log('🔐 开始管理员登录验证:', { username });
    
    // 查找管理员用户
    const adminUsers = getAdminUsers();
    console.log('📊 当前管理员用户数量:', adminUsers.length);
    
    if (adminUsers.length === 0) {
      console.error('❌ 没有找到任何管理员用户');
      return { success: false, message: '系统未初始化，请联系管理员' };
    }
    
    const user = adminUsers.find(u => 
      u.username === username && u.status === 'active'
    );
    
    if (!user) {
      console.error('❌ 管理员用户不存在或已禁用:', username);
      return { success: false, message: '用户名或密码错误' };
    }
    
    console.log('✅ 找到管理员用户:', user.username, '状态:', user.status);
    
    // 验证加密后的密码
    const encryptedPassword = encryptPassword(password);
    console.log('🔑 输入密码的哈希值:', encryptedPassword);
    console.log('🔑 数据库中的哈希值:', user.password);
    
    if (encryptedPassword !== user.password) {
      console.error('❌ 管理员密码错误');
      
      // 记录登录失败日志
      addLog({
        module: 'system',
        action: 'login',
        content: `管理员 ${username} 登录失败：密码错误`,
        operator: username,
        result: 'fail'
      });
      
      return { success: false, message: '用户名或密码错误' };
    }
    
    console.log('🎉 管理员登录验证成功');
    
    // 生成管理员专用token
    const token = `admin_${Date.now()}_${Math.random().toString(36).substring(7)}`;
    
    // 构建管理员用户信息，包含角色权限
    const adminUserInfo = {
      ...user,
      permissions: user.roles ? user.roles.flatMap(role => role.permissions || []) : []
    };
    
    // 记录登录成功日志
    addLog({
      module: 'system',
      action: 'login',
      content: `管理员 ${user.nickname || user.username} 登录系统`,
      operator: user.nickname || user.username,
      operatorId: user.id,
      result: 'success'
    });
    
    // 更新最后登录时间
    user.lastLoginTime = Date.now();
    const updatedUsers = adminUsers.map(u => u.id === user.id ? user : u);
    setAdminUsers(updatedUsers);
    
    console.log('✅ 管理员登录成功，返回数据:', { 
      token: token.substring(0, 20) + '...', 
      user: adminUserInfo.username 
    });
    
    return {
      success: true,
      data: {
        token,
        user: adminUserInfo
      },
      message: '登录成功'
    };
  },
  // 用户登录
  login: async (username, password) => {
    await delay();
    const users = getUsers(); // 从storage中获取用户列表
    const user = users.find(u => u.username === username && u.password === password);
    
    if (user) {
      return {
        success: true,
        data: {
          token: `token_${Date.now()}_${user.id}`,
          user
        }
      };
    }
    
    return { success: false, message: '用户名或密码错误' };
  },

  // 用户注册
  register: async (userData) => {
    await delay();
    
    // 调用storage.js中的addUser函数添加新用户
    const result = addUser({
      ...userData,
      id: Date.now(),
      createTime: Date.now(),
      points: 100,
      level: '普通会员',
      status: 'active'
    });
    
    if (!result.success) {
      return { success: false, message: result.message || '注册失败' };
    }
    
    const newUser = result.data;
    
    // 返回token和用户信息
    return {
      success: true,
      data: {
        token: `token_${Date.now()}_${newUser.id}`,
        user: newUser
      }
    };
  }
};

// 商品相关API
export const productAPI = {
  // 获取商品列表（前台用）
  getProducts: async (params = {}) => {
    await delay();
    let products = getProducts();
    
    // 前台只显示上架状态的商品
    if (!params.includeInactive) {
      products = products.filter(p => p.status === 'active');
    }
    
    // 搜索过滤
    if (params.keyword) {
      products = products.filter(p => 
        p.name.toLowerCase().includes(params.keyword.toLowerCase())
      );
    }
    
    // 分类过滤
    if (params.categoryId) {
      products = products.filter(p => p.categoryId === parseInt(params.categoryId));
    }
    
    // 后台管理：状态过滤
    if (params.status && params.includeInactive) {
      products = products.filter(p => p.status === params.status);
    }
    
    // 分页
    const page = params.page || 1;
    const pageSize = params.pageSize || 10;
    const start = (page - 1) * pageSize;
    const list = products.slice(start, start + pageSize);
    
    return {
      success: true,
      data: {
        list,
        total: products.length,
        page,
        pageSize
      }
    };
  },

  // 获取商品详情（前台用）
  getProductById: async (id) => {
    await delay();
    const products = getProducts();
    const product = products.find(p => p.id === parseInt(id));
    
    if (product && product.status === 'active') {
      // 增加浏览量
      product.views = (product.views || 0) + 1;
      setProducts(products);
      
      return { success: true, data: product };
    }
    
    return { success: false, message: '商品不存在或已下架' };
  },

  // 后台管理：获取所有商品（包括下架的）
  getAdminProducts: async (params = {}) => {
    await delay();
    let products = getProducts();
    
    // 搜索过滤
    if (params.keyword) {
      products = products.filter(p => 
        p.name.toLowerCase().includes(params.keyword.toLowerCase())
      );
    }
    
    // 分类过滤
    if (params.categoryId) {
      products = products.filter(p => p.categoryId === parseInt(params.categoryId));
    }
    
    // 状态过滤
    if (params.status) {
      products = products.filter(p => p.status === params.status);
    }
    
    // 分页
    const page = params.page || 1;
    const pageSize = params.pageSize || 10;
    const start = (page - 1) * pageSize;
    const list = products.slice(start, start + pageSize);
    
    return {
      success: true,
      data: {
        list,
        total: products.length,
        page,
        pageSize
      }
    };
  },

  // 添加商品
  addProduct: async (productData) => {
    await delay();
    const products = getProducts();
    
    const newProduct = {
      id: Date.now(),
      ...productData,
      createTime: Date.now(),
      sales: 0,
      views: 0,
      status: productData.status || 'active'
    };
    
    products.push(newProduct);
    setProducts(products);
    
    addLog({
      module: 'product',
      action: 'create',
      content: `添加商品：${newProduct.name}`,
      result: 'success'
    });
    
    return { success: true, data: newProduct };
  },

  // 更新商品
  updateProduct: async (id, productData) => {
    await delay();
    const products = getProducts();
    const index = products.findIndex(p => p.id === parseInt(id));
    
    if (index !== -1) {
      products[index] = { ...products[index], ...productData };
      setProducts(products);
      
      addLog({
        module: 'product',
        action: 'update',
        content: `更新商品：${products[index].name}`,
        result: 'success'
      });
      
      return { success: true, data: products[index] };
    }
    
    return { success: false, message: '商品不存在' };
  },

  // 删除商品
  deleteProduct: async (id) => {
    await delay();
    const products = getProducts();
    const product = products.find(p => p.id === parseInt(id));
    
    if (product) {
      const newProducts = products.filter(p => p.id !== parseInt(id));
      setProducts(newProducts);
      
      addLog({
        module: 'product',
        action: 'delete',
        content: `删除商品：${product.name}`,
        result: 'success'
      });
      
      return { success: true };
    }
    
    return { success: false, message: '商品不存在' };
  }
};

// 分类相关API
export const categoryAPI = {
  // 获取分类列表
  getCategories: async () => {
    await delay();
    const categories = getCategories();
    return { success: true, data: categories };
  },

  // 添加分类
  addCategory: async (categoryData) => {
    await delay();
    const categories = getCategories();
    
    const newCategory = {
      id: Date.now(),
      ...categoryData,
      createTime: Date.now(),
      productCount: 0
    };
    
    categories.push(newCategory);
    setCategories(categories);
    
    addLog({
      module: 'category',
      action: 'create',
      content: `添加分类：${newCategory.name}`,
      result: 'success'
    });
    
    return { success: true, data: newCategory };
  },

  // 更新分类
  updateCategory: async (id, categoryData) => {
    await delay();
    const categories = getCategories();
    const index = categories.findIndex(c => c.id === parseInt(id));
    
    if (index !== -1) {
      categories[index] = { ...categories[index], ...categoryData };
      setCategories(categories);
      
      addLog({
        module: 'category',
        action: 'update',
        content: `更新分类：${categories[index].name}`,
        result: 'success'
      });
      
      return { success: true, data: categories[index] };
    }
    
    return { success: false, message: '分类不存在' };
  },

  // 删除分类
  deleteCategory: async (id) => {
    await delay();
    const categories = getCategories();
    const category = categories.find(c => c.id === parseInt(id));
    
    if (category) {
      // 检查是否有子分类
      const hasChildren = categories.some(c => c.parentId === parseInt(id));
      if (hasChildren) {
        return { success: false, message: '该分类下有子分类，无法删除' };
      }
      
      // 检查是否有商品
      const products = getProducts();
      const hasProducts = products.some(p => p.categoryId === parseInt(id));
      if (hasProducts) {
        return { success: false, message: '该分类下有商品，无法删除' };
      }
      
      const newCategories = categories.filter(c => c.id !== parseInt(id));
      setCategories(newCategories);
      
      addLog({
        module: 'category',
        action: 'delete',
        content: `删除分类：${category.name}`,
        result: 'success'
      });
      
      return { success: true };
    }
    
    return { success: false, message: '分类不存在' };
  }
};

// 订单相关API
export const orderAPI = {
  // 更新完整订单信息（包括物流信息）
  updateOrder: async (orderId, orderData) => {
    await delay();
    
    const updatedOrder = updateAdminOrder(orderId, orderData);
    
    if (updatedOrder) {
      // 记录操作日志
      addLog({
        module: 'order',
        action: 'update',
        content: `更新订单 ${updatedOrder.orderNo} 信息`,
        result: 'success'
      });
      
      return {
        success: true,
        data: updatedOrder,
        message: '订单更新成功'
      };
    } else {
      return {
        success: false,
        message: '订单不存在'
      };
    }
  },
  // 获取订单列表
  getOrders: async (params = {}) => {
    await delay();
    let orders = getAdminOrders();
    
    // 搜索过滤
    if (params.orderNo) {
      orders = orders.filter(o => o.orderNo.includes(params.orderNo));
    }
    
    if (params.userName) {
      orders = orders.filter(o => o.userName.includes(params.userName));
    }
    
    if (params.status) {
      orders = orders.filter(o => o.status === params.status);
    }
    
    // 排序
    orders.sort((a, b) => b.createTime - a.createTime);
    
    // 分页
    const page = params.page || 1;
    const pageSize = params.pageSize || 10;
    const start = (page - 1) * pageSize;
    const list = orders.slice(start, start + pageSize);
    
    return {
      success: true,
      data: {
        list,
        total: orders.length,
        page,
        pageSize
      }
    };
  },

  // 更新订单状态
  updateOrderStatus: async (orderId, status) => {
    await delay();
    
    console.log('🔄 更新订单状态:', { orderId, status });
    
    try {
      // 更新前台用户订单状态
      const userOrders = getOrders();
      const userOrderIndex = userOrders.findIndex(o => o.id === parseInt(orderId));
      
      if (userOrderIndex !== -1) {
        const now = Date.now();
        userOrders[userOrderIndex].status = status;
        
        // 根据状态设置对应的时间戳
        if (status === 'paid') {
          userOrders[userOrderIndex].payTime = now;
        } else if (status === 'shipped') {
          userOrders[userOrderIndex].shipTime = now;
        } else if (status === 'delivered') {
          userOrders[userOrderIndex].deliverTime = now;
          
          // 确认收货时更新商品销量
          if (userOrders[userOrderIndex].products && userOrders[userOrderIndex].products.length > 0) {
            const { updateProductSales } = require('../utils/storage');
            userOrders[userOrderIndex].products.forEach(product => {
              updateProductSales(product.id, product.quantity);
              console.log(`✅ 商品 ${product.id} 销量已增加 ${product.quantity}`);
            });
          }
        } else if (status === 'cancelled') {
          userOrders[userOrderIndex].cancelTime = now;
        }
        
        setOrders(userOrders);
        console.log('✅ 前台订单状态已更新');
      }
      
      // 同时更新后台管理员订单状态
      const adminOrders = getAdminOrders();
      const adminOrderIndex = adminOrders.findIndex(o => o.id === parseInt(orderId));
      
      if (adminOrderIndex !== -1) {
        const now = Date.now();
        adminOrders[adminOrderIndex].status = status;
        
        // 根据状态设置对应的时间戳
        if (status === 'paid') {
          adminOrders[adminOrderIndex].payTime = now;
        } else if (status === 'shipped') {
          adminOrders[adminOrderIndex].shipTime = now;
        } else if (status === 'delivered') {
          adminOrders[adminOrderIndex].deliverTime = now;
        } else if (status === 'cancelled') {
          adminOrders[adminOrderIndex].cancelTime = now;
        }
        
        setAdminOrders(adminOrders);
        console.log('✅ 后台订单状态已更新');
      }
      
      // 记录操作日志
      addLog({
        module: 'order',
        action: 'update',
        content: `订单 ${orderId} 状态更新为：${status}`,
        result: 'success'
      });
      
      return { 
        success: true, 
        message: '订单状态更新成功' 
      };
      
    } catch (error) {
      console.error('❌ 更新订单状态失败:', error);
      return { 
        success: false, 
        message: '更新订单状态失败' 
      };
    }
  },
  // 创建订单
  createOrder: async (orderData) => {
    await delay();
    const order = addOrderToStorage(orderData);
    return createResponse(order, true, '订单创建成功');
  },

  // 获取订单状态中文
  getOrderStatusText: (status) => {
    const statusMap = {
      'pending': '待付款',
      'paid': '已付款',
      'shipped': '已发货',
      'delivered': '已完成', // 后台显示为已完成
      'cancelled': '已取消',
      'refunded': '已退款'
    };
    return statusMap[status] || status;
  },
};

// 用户相关API
export const userAPI = {
  // 获取用户列表
  getUsers: async (params = {}) => {
    await delay();
    let users = mockUsers;
    
    // 搜索过滤
    if (params.keyword) {
      users = users.filter(u => 
        u.username.includes(params.keyword) ||
        u.nickname?.includes(params.keyword) ||
        u.phone?.includes(params.keyword)
      );
    }
    
    if (params.level) {
      users = users.filter(u => u.level === params.level);
    }
    
    if (params.status) {
      users = users.filter(u => u.status === params.status);
    }
    
    // 分页
    const page = params.page || 1;
    const pageSize = params.pageSize || 10;
    const start = (page - 1) * pageSize;
    const list = users.slice(start, start + pageSize);
    
    return {
      success: true,
      data: {
        list,
        total: users.length,
        page,
        pageSize
      }
    };
  }
};

// 管理员用户相关API
export const adminUserAPI = {
  // 获取管理员列表
  getAdminUsers: async (params = {}) => {
    await delay();
    let adminUsers = getAdminUsers();
    
    // 搜索过滤
    if (params.keyword) {
      adminUsers = adminUsers.filter(u => 
        u.username.includes(params.keyword) ||
        u.nickname?.includes(params.keyword) ||
        u.email?.includes(params.keyword)
      );
    }
    
    if (params.roleId) {
      adminUsers = adminUsers.filter(u => 
        u.roles?.some(r => r.id === parseInt(params.roleId))
      );
    }
    
    if (params.status) {
      adminUsers = adminUsers.filter(u => u.status === params.status);
    }
    
    // 分页
    const page = params.page || 1;
    const pageSize = params.pageSize || 10;
    const start = (page - 1) * pageSize;
    const list = adminUsers.slice(start, start + pageSize);
    
    return {
      success: true,
      data: {
        list,
        total: adminUsers.length,
        page,
        pageSize
      }
    };
  },

  // 添加管理员
  addAdminUser: async (userData) => {
    await delay();
    const adminUsers = getAdminUsers();
    
    // 检查用户名是否存在
    if (adminUsers.find(u => u.username === userData.username)) {
      return { success: false, message: '用户名已存在' };
    }
    
    // 获取角色信息
    const roles = mockRoles.filter(r => userData.roleIds?.includes(r.id));
    
    const newUser = {
      id: Date.now(),
      ...userData,
      roles,
      createTime: Date.now(),
      status: userData.status || 'active'
    };
    
    adminUsers.push(newUser);
    setAdminUsers(adminUsers);
    
    addLog({
      module: 'user',
      action: 'create',
      content: `添加管理员：${newUser.nickname || newUser.username}`,
      result: 'success'
    });
    
    return { success: true, data: newUser };
  },

  // 更新管理员
  updateAdminUser: async (id, userData) => {
    await delay();
    const adminUsers = getAdminUsers();
    const index = adminUsers.findIndex(u => u.id === parseInt(id));
    
    if (index !== -1) {
      // 如果更新角色
      if (userData.roleIds) {
        userData.roles = mockRoles.filter(r => userData.roleIds.includes(r.id));
      }
      
      adminUsers[index] = { ...adminUsers[index], ...userData };
      setAdminUsers(adminUsers);
      
      addLog({
        module: 'user',
        action: 'update',
        content: `更新管理员：${adminUsers[index].nickname || adminUsers[index].username}`,
        result: 'success'
      });
      
      return { success: true, data: adminUsers[index] };
    }
    
    return { success: false, message: '用户不存在' };
  },

  // 删除管理员
  deleteAdminUser: async (id) => {
    await delay();
    const adminUsers = getAdminUsers();
    const user = adminUsers.find(u => u.id === parseInt(id));
    
    if (user) {
      if (user.username === 'superadmin') {
        return { success: false, message: '超级管理员不能删除' };
      }
      
      const newUsers = adminUsers.filter(u => u.id !== parseInt(id));
      setAdminUsers(newUsers);
      
      addLog({
        module: 'user',
        action: 'delete',
        content: `删除管理员：${user.nickname || user.username}`,
        result: 'success'
      });
      
      return { success: true };
    }
    
    return { success: false, message: '用户不存在' };
  },

  // 重置密码
  resetPassword: async (id, newPassword) => {
    await delay();
    const adminUsers = getAdminUsers();
    const user = adminUsers.find(u => u.id === parseInt(id));
    
    if (user) {
      // 这里应该保存加密后的密码
      user.password = newPassword;
      setAdminUsers(adminUsers);
      
      addLog({
        module: 'user',
        action: 'update',
        content: `重置管理员密码：${user.nickname || user.username}`,
        result: 'success'
      });
      
      return { success: true };
    }
    
    return { success: false, message: '用户不存在' };
  },

  // 修改密码
  changePassword: async (id, data) => {
    await delay();
    // 这里应该验证原密码并更新新密码
    
    addLog({
      module: 'user',
      action: 'update',
      content: '修改个人密码',
      result: 'success'
    });
    
    return { success: true };
  },

  // 更新个人信息
  updateProfile: async (id, data) => {
    await delay();
    const adminUsers = getAdminUsers();
    const index = adminUsers.findIndex(u => u.id === parseInt(id));
    
    if (index !== -1) {
      adminUsers[index] = { ...adminUsers[index], ...data };
      setAdminUsers(adminUsers);
      
      return { success: true, data: adminUsers[index] };
    }
    
    return { success: false, message: '用户不存在' };
  },

  // 获取登录日志
  getLoginLogs: async (userId) => {
    await delay();
    // 模拟登录日志
    return {
      success: true,
      data: [
        {
          id: 1,
          time: Date.now() - 1000 * 60 * 30,
          ip: '192.168.1.100',
          location: '北京市',
          device: 'Chrome on Windows',
          success: true
        },
        {
          id: 2,
          time: Date.now() - 1000 * 60 * 60 * 24,
          ip: '192.168.1.101',
          location: '上海市',
          device: 'Safari on Mac',
          success: true
        },
        {
          id: 3,
          time: Date.now() - 1000 * 60 * 60 * 24 * 2,
          ip: '192.168.1.102',
          location: '广州市',
          device: 'Chrome on Windows',
          success: false
        }
      ]
    };
  },

  // 获取操作统计
  getOperationStats: async (userId) => {
    await delay();
    // 模拟操作统计
    return {
      success: true,
      data: {
        today: 45,
        week: 280,
        month: 1200,
        total: 5680
      }
    };
  }
};

// 角色相关API
export const roleAPI = {
  // 获取角色列表
  getRoles: async () => {
    await delay();
    return { success: true, data: mockRoles };
  },

  // 添加角色
  addRole: async (roleData) => {
    await delay();
    const newRole = {
      id: Date.now(),
      ...roleData,
      createTime: Date.now()
    };
    
    mockRoles.push(newRole);
    
    addLog({
      module: 'role',
      action: 'create',
      content: `添加角色：${newRole.name}`,
      result: 'success'
    });
    
    return { success: true, data: newRole };
  },

  // 更新角色
  updateRole: async (id, roleData) => {
    await delay();
    const index = mockRoles.findIndex(r => r.id === parseInt(id));
    
    if (index !== -1) {
      mockRoles[index] = { ...mockRoles[index], ...roleData };
      
      addLog({
        module: 'role',
        action: 'update',
        content: `更新角色：${mockRoles[index].name}`,
        result: 'success'
      });
      
      return { success: true, data: mockRoles[index] };
    }
    
    return { success: false, message: '角色不存在' };
  },

  // 删除角色
  deleteRole: async (id) => {
    await delay();
    const role = mockRoles.find(r => r.id === parseInt(id));
    
    if (role) {
      if (role.code === 'super_admin') {
        return { success: false, message: '超级管理员角色不能删除' };
      }
      
      const index = mockRoles.findIndex(r => r.id === parseInt(id));
      mockRoles.splice(index, 1);
      
      addLog({
        module: 'role',
        action: 'delete',
        content: `删除角色：${role.name}`,
        result: 'success'
      });
      
      return { success: true };
    }
    
    return { success: false, message: '角色不存在' };
  }
};

// 售后相关API
export const refundAPI = {
  // 获取售后列表
  getRefunds: async (params = {}) => {
    await delay();
    let refunds = getRefunds();
    
    // 状态过滤
    if (params.status) {
      refunds = refunds.filter(r => r.status === params.status);
    }
    
    // 搜索过滤
    if (params.refundNo) {
      refunds = refunds.filter(r => r.refundNo.includes(params.refundNo));
    }
    
    if (params.orderNo) {
      refunds = refunds.filter(r => r.orderNo.includes(params.orderNo));
    }
    
    if (params.type) {
      refunds = refunds.filter(r => r.type === params.type);
    }
    
    // 排序
    refunds.sort((a, b) => b.createTime - a.createTime);
    
    // 分页
    const page = params.page || 1;
    const pageSize = params.pageSize || 10;
    const start = (page - 1) * pageSize;
    const list = refunds.slice(start, start + pageSize);
    
    return {
      success: true,
      data: {
        list,
        total: refunds.length,
        page,
        pageSize
      }
    };
  },

  // 获取售后统计
  getRefundStatistics: async () => {
    await delay();
    const refunds = getRefunds();
    
    const statistics = {
      pending: refunds.filter(r => r.status === 'pending').length,
      processing: refunds.filter(r => r.status === 'processing').length,
      approved: refunds.filter(r => r.status === 'approved').length,
      rejected: refunds.filter(r => r.status === 'rejected').length,
      totalAmount: refunds
        .filter(r => r.status === 'approved' || r.status === 'completed')
        .reduce((sum, r) => sum + (r.refundAmount || 0), 0)
    };
    
    return { success: true, data: statistics };
  },

  // 审核售后
  reviewRefund: async (id, reviewData) => {
    await delay();
    const refunds = getRefunds();
    const refund = refunds.find(r => r.id === parseInt(id));
    
    if (refund) {
      refund.status = reviewData.reviewResult;
      refund.reviewTime = Date.now();
      refund.reviewRemark = reviewData.reviewRemark;
      
      if (reviewData.reviewResult === 'approved') {
        refund.refundAmount = reviewData.refundAmount || refund.refundAmount;
        refund.returnAddress = reviewData.returnAddress;
      }
      
      setRefunds(refunds);
      
      addLog({
        module: 'refund',
        action: 'update',
        content: `审核售后单 ${refund.refundNo}：${reviewData.reviewResult === 'approved' ? '同意' : '拒绝'}`,
        result: 'success'
      });
      
      return { success: true };
    }
    
    return { success: false, message: '售后单不存在' };
  }
};

// Banner相关API
export const bannerAPI = {
  // 获取Banner列表
  getBanners: async () => {
    await delay();
    // 模拟Banner数据
    const banners = [
      {
        id: 1,
        image: 'https://img.alicdn.com/imgextra/i1/O1CN01YTRnJ21kYH3yFrbHi_!!6000000004694-2-tps-2500-600.png',
        title: '新品上市',
        link: '/app/product/1'
      },
      {
        id: 2,
        image: 'https://img.alicdn.com/imgextra/i2/O1CN01n7ybd91d0HV8kEPP4_!!6000000003677-0-tps-2500-600.jpg',
        title: '限时特惠',
        link: '/app/category/2'
      },
      {
        id: 3,
        image: 'https://img.alicdn.com/imgextra/i3/O1CN01Tnm1mu1OjSNVAKKtP_!!6000000001741-0-tps-2500-600.jpg',
        title: '品牌特卖',
        link: '/app/category/1'
      }
    ];
    
    return { success: true, data: banners };
  }
};

// 日志相关API
export const logAPI = {
  // 获取日志列表
  getLogs: async (params = {}) => {
    await delay();
    let logs = getLogs();
    
    // 搜索过滤
    if (params.operator) {
      logs = logs.filter(l => l.operator?.includes(params.operator));
    }
    
    if (params.module) {
      logs = logs.filter(l => l.module === params.module);
    }
    
    if (params.action) {
      logs = logs.filter(l => l.action === params.action);
    }
    
    if (params.result) {
      logs = logs.filter(l => l.result === params.result);
    }
    
    if (params.ipAddress) {
      logs = logs.filter(l => l.ipAddress?.includes(params.ipAddress));
    }
    
    // 时间范围过滤
    if (params.dateRange && params.dateRange.length === 2) {
      const [start, end] = params.dateRange;
      logs = logs.filter(l => 
        l.createTime >= new Date(start).getTime() &&
        l.createTime <= new Date(end).getTime()
      );
    }
    
    // 排序
    logs.sort((a, b) => b.createTime - a.createTime);
    
    // 分页
    const page = params.page || 1;
    const pageSize = params.pageSize || 20;
    const start = (page - 1) * pageSize;
    const list = logs.slice(start, start + pageSize);
    
    return {
      success: true,
      data: {
        list,
        total: logs.length,
        page,
        pageSize
      }
    };
  },

  // 获取日志统计
  getLogStatistics: async () => {
    await delay();
    const logs = getLogs();
    const now = Date.now();
    const today = new Date().setHours(0, 0, 0, 0);
    const week = now - 7 * 24 * 60 * 60 * 1000;
    const month = now - 30 * 24 * 60 * 60 * 1000;
    
    return {
      success: true,
      data: {
        today: logs.filter(l => l.createTime >= today).length,
        week: logs.filter(l => l.createTime >= week).length,
        month: logs.filter(l => l.createTime >= month).length,
        total: logs.length
      }
    };
  }
};